package dbs

import (
	"encoding/json"
	"github.com/jinzhu/gorm"
	"time"
)

type DbSession struct {
	ID        uint            `gorm:"primary_key"`
	UserID    uint            `gorm:"index"`
	K         string          `gorm:"type:varchar(64);not null;unique_index"`
	V         json.RawMessage `sql:"type:json" gorm:"not null"`
	Platform  string          `sql:"platform" gorm:"type:varchar(32);not null"`
	CreatedAt time.Time       `gorm:"type:datetime"`
	UpdatedAt time.Time       `gorm:"type:datetime"`
}

type S_Session_V struct {
	UserId     uint   `json:"user_id"`
	Phone      string `json:"phone"`
	Role       string `json:"role"`
	Gender     string `json:"gender"`
	Name       string `json:"name"`
	Department string `json:"department"`
	Platform   string `json:"platform"`
	OpenID     string `json:"open_id"`
}

type S_Session_List struct {
	UserID   uint   `json:"user_id"`
	K        string `json:"k"`
	Platform string `json:"platform"`
}

func (self *DbSession) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := (*db)

		if self.UserID != 0 {
			conn.Where("user_id = ? and platform = ?", self.UserID, self.Platform).Delete(self)
		}

		return conn.Create(&self).Error
	})
	return
}

func (self *DbSession) Get() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := (*db)

		if self.K != "" {
			conn = conn.Where("k = ?", self.K)
		}

		return conn.Find(&self).Error
	})
	return
}

func (self *DbSession) Query(s_list S_Session_List) (result []DbSession, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := (*db)

		// 查询 token 一般查询的是非当前 token 的记录
		if s_list.K != "" {
			conn = conn.Where("k <> ?", s_list.K)
		}

		if s_list.Platform != "" {
			conn = conn.Where("platform = ?", s_list.Platform)
		}

		if s_list.UserID != 0 {
			conn = conn.Where("user_id = ?", s_list.UserID)
		}

		return conn.Find(&result).Error
	})
	return
}

func (self *DbSession) Update(params map[string]interface{}) (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := (*db)

		return conn.Model(&self).Update(params).Error
	})
	return
}

func (self *DbSession) Delete() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := (*db)

		if self.UserID != 0 {
			conn = conn.Where("user_id = ?", self.UserID)
		}
		if self.Platform != "" {
			conn = conn.Where("platform = ? ", self.Platform)
		}

		// 顶号登录时避免删除自身 session
		if self.K != "" {
			conn = conn.Where("k <> ? ", self.K)
		}

		return conn.Delete(self).Error
	})
	return
}
